package cn.wen.forum.config;

import cn.wen.forum.common.util.StringUtils;
import cn.wen.forum.mapper.SysCodeMapper;
import cn.wen.forum.pojo.entity.SysCode;
import cn.wen.forum.pojo.entity.basic.SysCodeBasic;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SysLoadingConfig
 * @Author By wen
 * @Description 系统参数加载配置类
 * @Date 2023/8/14 16:05
 * @Version 1.0
 */
@Slf4j
@Component
public class InitSysParams implements ApplicationRunner {
    @Autowired
    private SysCodeMapper sysCodeMapper;

    /** 系统参数代码map*/
    private static final HashMap<String,String> cacheMap = new HashMap<>();

    /** 用户等级map*/
    private static final HashMap<String,String> levelCacheMap = new HashMap<>();

    /** 用户等级list*/
    private static final List<SysCode> levelCacheList = new ArrayList<>();

    @Override
    public void run(ApplicationArguments args) {
        log.info("-------开始加载系统参数--------");
        try {
            LambdaQueryWrapper<SysCode> wrapper = new LambdaQueryWrapper<>();
            wrapper.orderByAsc(SysCodeBasic::getId);
            List<SysCode> sysCodeList = sysCodeMapper.selectList(null);
            sysCodeList.forEach(sysCode -> {
                // 处理list,根据id获取name
                cacheMap.put(sysCode.getCodeId(),sysCode.getCodeValue());

                if(StringUtils.equals("0001",sysCode.getCodeType())){
                    // 处理等级list，将codeid也就是等级序号值作为key，condition作为value
                    levelCacheMap.put(sysCode.getCodeId().substring(3),sysCode.getCodeCondition());
                    levelCacheList.add(sysCode);
                }
            });
        } catch (Exception e) {
            log.error("系统参数加载失败,原因:",e);
        }
        log.info("-------加载系统参数初始化成功--------");
    }

    public static String getSysParamByID(String id) {
        return cacheMap.get(id) == null ? null : cacheMap.get(id);
    }

    public static Map<String, String> getLevelCacheMap() {
        return levelCacheMap;
    }

    public static List getLevelCacheList() {
        return levelCacheList;
    }

}
